package com.demo.base.tokenLogin.config;

import com.demo.base.tokenLogin.interceptor.CurrentUserInterceptor;
import com.demo.base.tokenLogin.resolver.CurrentUserResolver;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.InterceptorRegistration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.ArrayList;
import java.util.List;

/**
 * @author 曳戈泰尔
 * @version 1.0
 * @description * Web配置类 * 参数解析器 * 指定CurrentUserMethodArgumentResolver解析 * 配置拦截器
 * @date 2023/3/13 3:19 PM
 */
@Configuration
public class WebConfig implements WebMvcConfigurer {

    /** 注入拦截器 */
    private CurrentUserInterceptor currentUserInterceptor;

    @Autowired
    public void setCurrentUserInterceptor(CurrentUserInterceptor currentUserInterceptor) {
        this.currentUserInterceptor = currentUserInterceptor;
    }

    /**
     * 注入CurrentUserMethodArgumentResolver类为Bean
     *
     * @return
     */
    @Bean
    CurrentUserResolver currentUserMethodArgumentResolver() {
        return new CurrentUserResolver();
    }

    /**
     * 指定参数解析器
     *
     * @param argumentResolvers
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> argumentResolvers) {
        argumentResolvers.add(currentUserMethodArgumentResolver());
    }

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 注册Token拦截器
        InterceptorRegistration registration = registry.addInterceptor(currentUserInterceptor);

        // 所有路径都被拦截
        registration.addPathPatterns("/**");

        // 登录请求不拦截
        // 也可以通过 DisableToken 实现不拦截
        registration.excludePathPatterns("/user/login");

        // 放行Knife4j接口文档
        List<String> excludePaths = new ArrayList<>();
        excludePaths.add("/doc.html");
        excludePaths.add("/swagger-resources");
        excludePaths.add("/webjars/**");
        excludePaths.add("/favicon.ico");
        excludePaths.add("/v3/**");
        registration.excludePathPatterns(excludePaths);
    }
}
